package miiteen.customsportal.login.controller;

import cn.gov.customs.casp.config.ConfigReader;
import cn.gov.customs.casp.sdk.h4a.BeanReaderHelper;
import cn.gov.customs.casp.sdk.h4a.entity.ObjectParentOrganizations;
import cn.gov.customs.casp.sdk.h4a.entity.ObjectsDetail;
import cn.gov.customs.casp.sdk.h4a.enumdefines.ViewCategory;
import cn.gov.customs.casp.sdk.h4a.ogu.ws.IOguReaderGetObjectParentOrganizationsCupaaFaultArgsFaultFaultMessage;
import cn.gov.customs.casp.sdk.h4a.ogu.ws.IOguReaderGetObjectsDetailCupaaFaultArgsFaultFaultMessage;
import cn.gov.customs.casp.sdk.h4a.ogu.ws.ObjectCategory;
import cn.gov.customs.casp.sdk.h4a.ogu.ws.OrganizationCategory;
import cn.gov.customs.casp.sdk.h4a.passport.IOguBeanReader;
import cn.gov.customs.casp.sdk.h4a.sso.passport.Ticket;
import cn.gov.customs.casp.sdk.h4a.sso.passport.util.CommonHelper;
import cn.gov.customs.casp.sdk.h4a.sso.passport.util.ParsTicketUtil;
import cn.gov.customs.casp.sdk.h4a.sso.passport.util.PassportManager;
import cn.gov.customs.casp.sdk.h4a.util.H4aDefaultConstants;
import miiteen.core.configuration.MeetingProperties;
import miiteen.core.result.ResultMessage;
import miiteen.core.result.ResultMessageTool;
import miiteen.customsportal.basic.beans.BasicPageBrowsing;
import miiteen.customsportal.basic.service.BasicPageBrowsingService;
import miiteen.customsportal.login.beans.LoginOrganizationInfo;
import miiteen.customsportal.login.beans.LoginUserInfo;
import miiteen.customsportal.login.beans.UserInfo;
import miiteen.customsportal.login.service.LoginIndexService;
import miiteen.customsportal.login.service.LoginUserInfoService;

import miiteen.demo.utils.IPUtils;
import miiteen.sys.base.controller.BaseAction;
import miiteen.sys.cache.LoginInfoCache;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Controller
@CrossOrigin
public class LoginIndexController extends BaseAction {

    @Autowired
    private LoginIndexService loginIndexService;

    @GetMapping("/login")
    public String login(HttpServletRequest request) {
        String ticket = request.getParameter("token");
        //加载用户信息
        UserInfo userInfo = loadUserInfo(ticket,request);
        //将用户信息保存到缓存
        String token = UUID.randomUUID().toString().replace("-", "");
        LoginInfoCache.set(token, userInfo);
        //跳转门户主页
        String pageUrl = MeetingProperties.getConfigByKey("login.loginIndex") + "?token=" + token;
        return "redirect:" + pageUrl;
    }

    @GetMapping("/getUser")
    @ResponseBody
    public ResultMessage<UserInfo> getUser(HttpServletRequest request) {
        String token = request.getHeader("token");
        UserInfo userInfo = LoginInfoCache.get(token);
        return ResultMessageTool.Success("", userInfo == null ? new UserInfo() : userInfo);
    }

    /**
     * 加载登录用户信息
     *
     * @param token
     */
    private UserInfo loadUserInfo(String token,HttpServletRequest request) {
        String ticketStr = CommonHelper.decryptTicket(token);
        Ticket ticket = ParsTicketUtil.getTicketUtil(ticketStr);
        return loginRecord(ticket,request);
    }

    /**
     * 保存登录信息并返回登录用户信息
     *
     * @param ticket
     * @return
     */
    public UserInfo loginRecord(Ticket ticket,HttpServletRequest request) {
        UserInfo userInfo = new UserInfo();
        //获取用户信息并保存登录记录
        StringBuffer userId = new StringBuffer();
        userId.append(ticket.getLn());
        userId.append("&");
        userId.append(ticket.getAbm());
        //获取登录信息
        String objectDetailsLastParam = ConfigReader.getConfigValue("h4a-config.xml", "object_param", "parameter_obj", "getBeanObjectsDetail_lastParam");
        String organizationLastParam = ConfigReader.getConfigValue("h4a-config.xml", "object_param", "parameter_obj", "organizationCategory_lastParam");
        if (null == objectDetailsLastParam) {
            objectDetailsLastParam = "";
        }
        if (null == organizationLastParam) {
            organizationLastParam = "";
        }
        IOguBeanReader oguBeanReaderHelper = BeanReaderHelper.getIOguBeanReader();
        try {
            ObjectsDetail[] objectDetails = oguBeanReaderHelper.getBeanObjectsDetail(
                    H4aDefaultConstants.DEFAULT_BASE_VIEW,
                    ViewCategory.ViewCode, userId.toString(),
                    ObjectCategory.USER_IDENTITY, "",
                    OrganizationCategory.NONE, objectDetailsLastParam);
            if (null != objectDetails && objectDetails.length > 0) {
                ObjectsDetail objectDeatil = objectDetails[0];//这里为了编写示例默认取第一个人员，默认第一个是主职，其他都是兼职，
                //返回用户信息
                userInfo.setUserId(objectDeatil.getUser_guid());
                userInfo.setUserName(URLEncoder.encode(objectDeatil.getDisplay_name(), "utf-8"));
                userInfo.setPosition(URLEncoder.encode(objectDeatil.getAll_path_name(), "utf-8"));
                userInfo.setJobNo(objectDeatil.getPerson_id());
                //如果业务系统需要使用到兼职用户需要自行编写业务逻辑实现兼职用户的情况
                ObjectParentOrganizations[] objectOrganizations = oguBeanReaderHelper.getBeanObjectParentOrganizations(
                        H4aDefaultConstants.DEFAULT_BASE_VIEW,
                        ViewCategory.ViewCode, objectDeatil.getAll_path_name(),
                        ObjectCategory.USER_ALL_PATH_NAME, "",
                        OrganizationCategory.NONE, false, false,
                        "", organizationLastParam);
                if (null != objectOrganizations && objectOrganizations.length > 0) {
                    //保存登录信息
                    loginIndexService.saveLoginUser(objectDeatil, objectOrganizations);
                    BasicPageBrowsing basicPageBrowsing = new BasicPageBrowsing();
                    basicPageBrowsing.setJobNo(objectDeatil.getPerson_id());
                    basicPageBrowsing.setUserName(objectDeatil.getDisplay_name());
                    basicPageBrowsing.setDelstate(0);
                    loginIndexService.addPageBrowsing(basicPageBrowsing, request);
                }
            }
        } catch (IOguReaderGetObjectsDetailCupaaFaultArgsFaultFaultMessage | IOguReaderGetObjectParentOrganizationsCupaaFaultArgsFaultFaultMessage /*| IAccreditReaderGetFunctionsOfUserCupaaFaultArgsFaultFaultMessage*/ e) {
            e.printStackTrace();
        } finally {
            return userInfo;
        }
    }

    private String getCookieValue(String name, HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        String cookieValue = null;
        if (cookies == null) {
            return cookieValue;
        }
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals(name)) {
                cookieValue = cookie.getValue();
                break;
            }
        }
        return cookieValue;
    }
}
